﻿/**
 * 表单控制
 */
var FormBuilder = new Class({
	
	initialize : function(baseArea){
	},
	
	/**
	 * 生成创建联系人表单控件
	 * @return {element} 创建联系人FORM控件
	 */
	buildCreateForm : function(){
		var choiceForm = new ChoiceForm();
		choiceForm.addEvent('onAffirm', function(){
			this.closeForm(choiceForm.baseDiv);
		}.bind(this));
		formAction.submitCreate(choiceForm);
		return choiceForm.build('正在创建联系人…');
	},
	
	/**
	 * 生成删除联系人的选择菜单
	 * @param {int} id 要删除的联系人ID
	 * @return {element} 选择菜单
	 */
	buildDeleChoice : function(id){
		var choiceForm = new ChoiceForm();
		choiceForm.addEvent('onYes', function(){
			formAction.submitDelete(id, choiceForm);
		}.bind(this));
		choiceForm.addEvent('onNo', function(){
			this.closeForm(choiceForm.baseDiv);
		}.bind(this));
		choiceForm.addEvent('onAffirm', function(){
			this.closeForm(choiceForm.baseDiv);
		}.bind(this));
		return choiceForm.build('您确实要删除这条记录么？', [
			{'name': 'yes', 'value': '确定'},
			{'name': 'no', 'value': '取消'}
		]);
	},
	
	/**
	 * 生成编辑联系人表单控件
	 * @param {int} id 联系人ID
	 * @return {element} 编辑联系人FORM控件
	 */
	buildEditForm : function(id){
		var CreatFormElmt = new Element('form', {'id':'editForm'});
		var idBox = new Element('input', {'id': 'id', 'type': 'hidden', 'value': id}).injectInside(CreatFormElmt);
		CreatFormElmt.addEvent('submit', function(e){
			e = new Event(e).stop();
			formAction.submitEdit(CreatFormElmt);
		}.bind(this));
		new Element('h2').injectInside(CreatFormElmt).setHTML('编辑联系人');
		var infoElmt = new Element('div',{
			'class' : 'infoArea'
		})
		.injectInside(CreatFormElmt)
		.setText('资料下载中…');
		
		dataCommunication.getEditData(id, function(result){
			try{
				var data = Json.evaluate(result);
				if (!data.isSucceed) {
					infoElmt.setText(data.message);
					this.closeForm.delay(2000, this, CreatFormElmt);
					return false;
				}
				this.buildBasicInputs(data.data.basicData).injectInside(CreatFormElmt);
				this.buildCustomInputs(data.data.customData).injectInside(CreatFormElmt);
				this.buildRemarkInputs(data.data.remarkData).injectInside(CreatFormElmt);
				this.buildButtons().injectInside(CreatFormElmt);
				infoElmt.remove();
			}catch(e) {
				infoElmt.setText('数据解析错误.'+e.message);
			}
		}.bind(this), infoElmt);
		return CreatFormElmt;
	},
	
	/**
	 * 生成表单按钮控件
	 * @return {element} 装载表单按钮的DIV控件
	 */
	buildButtons : function(valuePack){
		var buttonPlace = this.buildPlace('');
		var submit = new Element('input', {'type': 'submit', 'value': '提交', 'class': 'button submitButton'}).injectInside(buttonPlace);
		var cancel = new Element('input', {'type': 'button', 'value': '取消', 'class': 'button closeButton'}).injectInside(buttonPlace);
		cancel.addEvent('click', function(e){
			e = new Event(e).stop();
			closeElmt = e.target.getParent();
			return this.closeForm(closeElmt);
		}.bind(this));
		return buttonPlace;
	},
	
	/**
	 * 生成基本信息输入表单
	 * @return {element} 包含基本内容输入控件的DIV
	 */
	buildBasicInputs : function(valuePack){
		var baseDiv = new Element('div', {'id': 'basicArea', 'class':'placeArea'});
		var title = new Element('h4').setText('基本信息').injectInside(baseDiv);
		//姓名
		var namePlace = this.buildPlace('* 姓名：').injectInside(baseDiv);
		var nameInput = new Element('input', {'id': 'name', 'name': 'name', 'type': 'text', 'class': 'input'}).injectInside(namePlace);
		//生日
		var birthdayPlace = this.buildPlace('生日：').injectInside(baseDiv);
		var birthdayInput = new Element('input', {'id': 'birthday', 'name': 'birthday', 'type': 'text', 'class': 'input'}).injectInside(birthdayPlace);
		//性别
		var sexPlace = this.buildPlace('性别：').injectInside(baseDiv);
		var sexInput = new Element('select', {'id': 'sex', 'name': 'sex', 'class': 'input selectInput'}).injectInside(sexPlace);
		['','男','女'].each(function(value){new Element('option', {'value': value}).setHTML(value||'请选择…').injectInside(sexInput);});
		sexInput.trim = function(){
			$ES('option', this).each(function(option){
				if (!option.value && sexInput.value) option.remove();
			});
		};
		sexInput.addEvent('change', sexInput.trim);
		this.buildInfoElmt(baseDiv);
		this.setValues(baseDiv, valuePack);
		sexInput.trim();
		return baseDiv;
	},
	
	/**
	 * 生成自定义信息输入表单
	 * @return {element} 包含自定义信息输入表单的DIV
	 */
	buildCustomInputs : function(valuePack){
		valuePack = valuePack || [
			{'id': '0', 'title': '办公电话', 'content': ''},
			{'id': '0', 'title': '移动电话', 'content': ''}
		]
		var baseDiv = new Element('div', {'id': 'customArea', 'class':'placeArea'});
		var title = new Element('h4').setText('联系方式').injectInside(baseDiv);
		valuePack.each(function(value){
			this.buildCustomPlace(value).injectInside(baseDiv);
		}.bind(this));
		var buttonPlace = this.buildPlace().injectInside(baseDiv);
		var addPlaceButton = new Element('input', {'type': 'button', 'value': '+ 增加', 'class': 'button'}).injectInside(buttonPlace);
		addPlaceButton.addEvent('click', function(){
			this.buildCustomPlace().injectBefore(buttonPlace);
		}.bind(this));
		return baseDiv;
	},
	
	/**
	 * 生成备注信息输入表单
	 * @param {Object} 装载备注信息内容的数据包, 包括(
	 *     {string} content 备注信息字符串
	 * )
	 * @return {element} 包含备注信息输入表单的DIV
	 */
	buildRemarkInputs : function(valuePack){
		valuePack = valuePack || {};
		var baseDiv = new Element('div', {'id': 'remarkArea', 'class':'placeArea'});
		var title = new Element('h4').setText('备注').injectInside(baseDiv);
		var remarkPlace = this.buildPlace('').injectInside(baseDiv);
		var remarkInput = new Element('textarea', {'id': 'remark', 'name': 'remark', 'class': 'input textareaInput'}).injectInside(remarkPlace);
		new Element('div').setStyle('display', 'none').addClass('info').injectInside(remarkPlace);
		remarkInput.value = valuePack.content || '';
		return baseDiv;
	},
	
	/**
	 * 生成一条自定义信息表单块
	 * @param {Object} value 装载表单默认值的数据包, 包括(
	 *     {int} id 自定义信息ID, 默认为0
	 *     {string} title 自定义信息标题, 默认为"未定义"
	 *     {string} content 自定义信息内容, 默认为空字符串
	 * )
	 * @return {element} 装载输入控件的DIV控件
	 */
	buildCustomPlace : function(value){
		value = value || {'id': '0'};
		var newLabel = new Element('div', {'class': 'inputPlace'});
		var idBox = new Element('input', {
			'type' : 'hidden',
			'class': 'customIdBox',
			'value': value.id
		}).injectInside(newLabel);
		var title = new PlaceEditor(
			{'defaultText': (value.title || '未定义'), 'class': 'customTitle'},
			{'class': 'customTitleInput'},
			{'class': 'customTitleValueBox'}
		).build().inject(newLabel);
		var content = new Element('input', {
			'type' : 'text',
			'class': 'customContent'
		}).injectInside(newLabel);
		new Element('div')
		.setStyle('display', 'none')
		.addClass('info')
		.injectInside(newLabel);
		content.value = value.content || '';
		return newLabel;
	},
	
	/**
	 * 生成装载内容用的DIV控件
	 * @param {string} explain 标题说明信息, 默认为空字符串
	 * @return {element} 包含加载了指定说明信息的DIV控件
	 */
	buildPlace : function(explain){
		var newLabel = new Element('div', {'class': 'inputPlace'});
		var explain = new Element('div')
		.addClass('explain')
		.injectInside(newLabel)
		.setHTML(explain || '');
		return newLabel;
	},
	
	/**
	 * 生成一个装载指定INPUT控件的LABEL控件
	 * @param {string} explain 说明信息, 默认为空字符串
	 * @param {Object} props INPUT控件的设定参数
	 * @return {element} LABEL控件
	 */
	buildLabelPack : function(explain, props){
		var newPack = new Element('label',{'class': 'lablePack'}).setHTML(explain);
		new Element('input', props).injectTop(newPack);
		return newPack
	},
	
	/**
	 * 为控件中的项目增加信息控件(查找所有class为"inputPlace"的控件并向其中插入class为"info"的DIV控件)
	 * @param {element} baseElmt 装载输入项目的控件
	 */
	buildInfoElmt : function(baseElmt){
		var places = $ES('div[class=inputPlace]', baseElmt);
		places.each(function(place){
			new Element('div')
			.setStyle('display', 'none')
			.addClass('info')
			.injectInside(place);
		});
	},
	
	/**
	 * 为指定控件中包含的输入控件设定默认值
	 * @param {element} baseElmt 装载输入控件的控件
	 * @param {Object} valuePack 装载默认值的数据包
	 */
	setValues : function(baseElmt, valuePack){
		if (!valuePack) return false;
		var places = $ES('div[class=inputPlace]', baseElmt);
		places.each(function(place){
			var inputElmt = $ES('input,textarea,select', place);
			if (!inputElmt.length) return false;
			if (inputElmt.length > 1) {
				inputElmt.each(function(item){
					if (item.value == valuePack[item.id]) {
						item.setProperty('checked', true);
					}
				});
			} else {
				inputElmt[0].value = valuePack[inputElmt[0].id] || '';
			}
		});
		return true;
	},
	
	/**
	 * 为指定的FORM控件中增加一个显示指定信息用的DIV控件, 或更新该控件的内容
	 * @param {element} form 要显示信息的FORM控件
	 * @param {string} infoString 要显示的信息内容, 若为空则隐藏信息控件
	 * @param {Object} className 信息控件的class, 默认为normal
	 */
	setFormInfo : function(form, infoString, className){
		var infoElmt = $E('div[class^=formInfo]', form);
		if (!infoElmt) {
			infoElmt = new Element('div')
			.setStyle('display', 'none')
			.injectAfter($E('h2', form));
		}
		infoElmt
		.setHTML(infoString)
		.setProperty('class', 'formInfo')
		.addClass(className || 'normal')
		.setStyle('display', infoString? '' : 'none');
	},
	
	/**
	 * 以指定的控件为基础向上搜索, 当遇到父控件有close方法时则执行, 用以关闭FORM表单界面
	 * @param {Object} closeElmt 向上搜索的基础控件
	 * @return {bool} 如果成功找到close并执行则返回True, 否则返回False
	 */
	closeForm : function(closeElmt){
		try {
			while ($type(closeElmt.close || false) != 'function') {
				closeElmt = closeElmt.getParent();
			}
			if(closeElmt.close) closeElmt.close();
			return true;
		} catch(e){
			return false;
		}
	}
});

/**
 * 选择菜单类
 */
var ChoiceForm = new Class({
	
	/**
	 * 生成选择菜单控件并返回
	 * @param {string} infomation 选择菜单的提示信息
	 * @param {array} buttons 包含按钮信息的数组，按钮信息包括：(
	 *     {string} name 按钮名（当按钮被按下时会产生按钮事件，如按钮名为yes，事件名为onYes）
	 *     {string} value 按钮的文字内容
	 * )
	 * @return {element} 返回生成出来的菜单DIV控件
	 */
	build : function(infomation, buttons){
		this.baseDiv = new Element('div', {'class': 'choiceForm'});
		this.infoDiv = new Element('div', {'class': 'info'}).setText(infomation || '').injectInside(this.baseDiv);
		this.buttons = [];
		buttons = buttons || [];
		buttons.each(function(button){
			this.buttons.push(new Element('input', {'type': 'button', 'class': 'button '+button.name, 'value': button.value})
			.injectInside(this.baseDiv)
			.addEvent('click', function(e){
				e = new Event(e).stop();
				this.fireEvent('on'+button.name.capitalize());
				this.hideButtons();
			}.bind(this)));
		}.bind(this));
		return this.baseDiv;
	},
	
	/**
	 * 设定带确定按钮的菜单提示信息
	 */
	setAffirmInfo : function(infoString){
		this.setInfo(infoString);
		new Element('input', {'type': 'button', 'class': 'button', 'value': '确定'})
		.injectInside(this.baseDiv)
		.addEvent('click', function(){
			this.fireEvent('onAffirm');
		}.bind(this));
		return this;
	},
	
	/**
	 * 设定菜单提示信息
	 */
	setInfo : function(infoString){
		this.infoDiv.setText(infoString);
		return this;
	},
	
	/**
	 * 隐藏所有按钮
	 */
	hideButtons : function(){
		this.buttons.each(function(button){
			button.setStyle('display', 'none');
		});
		return this;
	}
})
.implement(new Events);